package xin.petstore.framework.interceptor;

import xin.petstore.framework.annotation.Token;
import xin.petstore.framework.cas.SessionUtils;

import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 防止表单重复提交
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if ((handler instanceof HandlerMethod)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Token annotation = (Token) handlerMethod.getMethodAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.saveToken();
                if (needSaveSession) {
                    SessionUtils.getSession().setAttribute("token", UUID.randomUUID().toString());
                }
                boolean needRemoveSession = annotation.removeToken();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        if (StringUtils.isNotEmpty(annotation.sendRedirectUrl())) {
                            response.sendRedirect(annotation.sendRedirectUrl());
                        }
                        return false;
                    }
                    SessionUtils.getSession().removeAttribute("token");
                }
            }
            return true;
        }
        return super.preHandle(request, response, handler);
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) SessionUtils.getSession().getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) {
            return true;
        }
        return !serverToken.equals(clinetToken);
    }
}
